package org.itsolutions.javaBackup.ftp.handler;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.itsolutions.javaBackup.exceptions.AException;
import org.itsolutions.javaBackup.exceptions.FTPException;
import org.itsolutions.javaBackup.logger.ELogLevel;
import org.itsolutions.javaBackup.logger.ILogger;
import org.itsolutions.javaBackup.logger.LoggerHelper;
import org.itsolutions.javaBackup.spi.backup.ftp.FTPFileWrapper;
import org.itsolutions.javaBackup.spi.backup.ftp.IFTPDownloadHandler;

/**
 * 
 * @author Tomas Fecko
 */
public final class FTPDownloadHandler implements IFTPDownloadHandler {

	private static final ILogger LOGGER = LoggerHelper.getLogger(FTPDownloadHandler.class);
	private FTPClient 			 mFtpClient;

	@Override
	public void connect(String pServer, String pUsername, String pPassword) throws AException {
		try {
			mFtpClient = new FTPClient();
			mFtpClient.connect(pServer);
			int replyCode = mFtpClient.getReplyCode();

			if (!FTPReply.isPositiveCompletion(replyCode)) {
				mFtpClient.disconnect();
				throw new FTPException("FTP server refused connection.");
			}
			if (!mFtpClient.login(pUsername, pPassword)) {
				mFtpClient.logout();
				throw new FTPException("Problem during login.");				
			}
			// Connect and logon to FTP Server
			LOGGER.log(ELogLevel.DEBUG, "Connected to ", pServer, " ReplyString:", mFtpClient.getReplyString());
		} catch (SocketException e) {
			LOGGER.log(ELogLevel.ERROR, e);
			throw new FTPException(e);
		} catch (IOException e) {
			LOGGER.log(ELogLevel.ERROR, e);
			throw new FTPException(e);
		}
	}

	@Override	
	public List<FTPFileWrapper> getListOfFiles(String pFolder) throws AException {
		if (mFtpClient != null && mFtpClient.isConnected()) {
			try {
				if (mFtpClient.changeWorkingDirectory(pFolder)) {
					List<FTPFileWrapper> returnList = new ArrayList<FTPFileWrapper>();
					FTPFile[] files = mFtpClient.listFiles();
					for (FTPFile file : files) {
						returnList.add(FTPHelper.createFileWrapper(file));
					}
					return returnList;
				} else {
					throw new FTPException("Changing the directory unsuccessfull.");
				}
			} catch (IOException e) {
				LOGGER.log(ELogLevel.ERROR, e);
				throw new FTPException(e);
			} 
		} else {
			throw new FTPException("FTPClient is not connected, connect first !!!");
		}
	}
	

//	public static void getDataFiles(String server, String username, String password, String folder, String destinationFolder,
//			Calendar start, Calendar end ) {
//		try {
//			// List the files in the directory
//
//
//			System.out.println("Number of files in dir: " + files.length);
//			DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
//			for (int i = 0; i < files.length; i++) {
//				Date fileDate = files[ i ].getTimestamp().getTime();
//				if (fileDate.compareTo(start.getTime()) >= 0 && fileDate.compareTo(end.getTime()) <= 0) {
//					// Download a file from the FTP Server
//					System.out.print(df.format(files[ i ].getTimestamp().getTime()));
//					System.out.println("\t" + files[ i ].getName());
//					File file = new File(destinationFolder + File.separator + files[ i ].getName());
//					FileOutputStream fos = new FileOutputStream(file); 
//					ftp.retrieveFile(files[ i ].getName(), fos);
//					fos.close();
//					file.setLastModified(fileDate.getTime());
//				}
//			}
//		} catch (Exception e) {
//			LOGGER.log(ELogLevel.ERROR, e);
//		}
//	}

	@Override
	public void disconnect() throws AException {
		if (mFtpClient != null && mFtpClient.isConnected()) {
			try {
				mFtpClient.logout();
				mFtpClient.disconnect();
			} catch (IOException e) {
				LOGGER.log(ELogLevel.ERROR, e);
				throw new FTPException(e);
			}
		} else {
			throw new FTPException("FTPClient is not connected, connect first !!!");
		}		
	}
}





